import {
  deleteMenu,
  exportMenu,
  fetchMenuById,
  fetchMenuList,
} from '@/api/modules/system/menu/menu';
import { getParentMenus } from '@/api/modules/system/menu/utils';
import { convertMenuDataToTree } from '@/utils/common/tree';
import { response } from '@/utils/table/table';
import { menuForm, menuResetForm, menuShowForm } from './form';
import { menuTable, menuTree } from './table';

export const menuList = async () => {
  try {
    menuTable.value.loading = true;
    const { data } = await fetchMenuList(menuTable.value.query.menuName);
    if (data.data) {
      let treeData = convertMenuDataToTree(data.data);
      menuTable.value.data = treeData;
      menuTable.value.query.total = treeData.length;
      menuTable.value.loading = false;
    }
  } catch (error) {
    menuTable.value.loading = false;
  }
};

export const menuEdit = async (id?: number) => {
  let targetId = id ? id : menuTable.value.keys[0];
  menuTable.value.loading = true;

  try {
    const { data } = await fetchMenuById(targetId);
    await menuCreate();
    if (data.data) {
      menuForm.value = data.data;
      menuShowForm.value = true;
      menuTable.value.loading = false;
    }
  } catch (error) {
    menuTable.value.loading = false;
  }
};

/**
 * @description: 创建菜单，构建父目录
 */
export const menuCreate = async () => {
  menuResetForm();
  menuTree.value = await getParentMenus();
  menuShowForm.value = true;
};

export const menuDelete = async (id?: number) => {
  let ids = id ? [id] : menuTable.value.keys;
  await response(deleteMenu, ids);
  await menuList();
  menuTable.value.keys = [];
};

// 导出EXCEL文件
export const menuExport = () => {
  return exportMenu({
    pageNum: menuTable.value.query.pageNum,
    pageSize: menuTable.value.query.pageSize,
  });
};
export const createSubMenu = async (parentId: number) => {
  menuCreate();
  menuForm.value.parentId = parentId;
  menuShowForm.value = true;
};
